
import asyncio
from agent.streaming_agent import StreamingChatbot, EventType
import logging
logging.getLogger("streamlit").setLevel(logging.ERROR)


async def console_app(query: str):
    print("🧠实时响应智能体示例")
    print("=" * 50)

    chatbot = StreamingChatbot(verbose=False, mode="hybrid", enable_reflection=True)
    config = {
        "mcpServers": {
            "gaode": {
                "url": "https://mcp.amap.com/sse?key=8cf6bb2894f75c5df1671d84c15b3926",
            }
        }
    }
    await chatbot.agent.tool_manager.load_mcp_tools(config)

    print(f"❓ Question: {query}")
    print("-" * 50)

    step_count = 0

    async for event in chatbot.chat_stream(query, session_id="123", max_steps=5):

        await asyncio.sleep(0)

        if event.type == EventType.THINKING_START:
            step_count += 1
            print(f"🤔 Step {step_count}：开始思考...")

        elif event.type == EventType.THINKING:
            thought = event.data.get("thought", "")
            print(f"💭 想法： {thought[:100]}{'...' if len(thought) > 100 else ''}")

        elif event.type == EventType.ACTION_PLANNED:
            action = event.data.get("action", "")
            action_input = event.data.get("input", "")
            print(f"📋 动作规划：`{action}`，输入参数：`{action_input}`")

        elif event.type == EventType.ACTION_START:
            action = event.data.get("action", "")
            action_input = event.data.get("input", "")
            print(f"🔧 调用工具：`{action}`，输入参数：`{action_input}`")

        elif event.type == EventType.ACTION_RESULT:
            result = event.data.get("result", {})
            if result.get("success"):
                print(f"✅ 工具调用成功 !")
            else:
                print(f"❌ 工具调用失败 ! {result.get('error', '未知错误')}")

        elif event.type == EventType.OBSERVATION:
            observation = event.data.get("observation", "")
            print(f"👁️ 洞察：{observation}")

        elif event.type == EventType.PLAN_CREATED:
            plan = event.data.get("plan", {})
            print(f"📋 计划创建完成。计划描述：{plan.get('description', '无计划')}")
            steps = plan.get("steps", [])
            if steps:
                print("步骤：")
                for i, step in enumerate(steps, 1):
                    print(f"{i}. {step.get('tool', '未知')}：{step.get('description', '无描述')}")

        elif event.type == EventType.PLAN_STEP_START:
            step_desc = event.data.get("step_description", "")
            tool = event.data.get("tool", "")
            plan_step = event.data.get("plan_step", 0)
            total_steps = event.data.get("total_steps", 0)
            print(f"执行计划 {plan_step}/{total_steps}：调用工具：`{tool}`")
            print(f"_{step_desc}_")

        elif event.type == EventType.PLAN_STEP_COMPLETE:
            print(f"✅ 计划执行完毕！")

        elif event.type == EventType.REFLECTION_START:
            quality_threshold = event.data.get("quality_threshold", 0.7)
            print(f"🔍 开始反思 (当前质量阈值：{quality_threshold:.2f})...")

        elif event.type == EventType.REFLECTION_CRITIQUE:
            iteration = event.data.get("iteration", 1)
            critique = event.data.get("critique", {})
            quality = critique.get("overall_quality", 0.0)
            confidence = critique.get("confidence", 0.0)
            needs_refinement = critique.get("needs_refinement", False)

            if quality >= 0.8:
                quality_text = f"质量得分：{quality:.2f} (优秀)"
            elif quality >= 0.7:
                quality_text = f"质量得分：{quality:.2f} (良好)"
            elif quality >= 0.5:
                quality_text = f"质量得分：{quality:.2f} (需要改进)"
            else:
                quality_text = f"质量得分：{quality:.2f} (低)"

            print(f"🤔 反思批评-迭代 {iteration}：{quality_text}，置信度：{confidence:.2f}，"
                  f"需要完善：{'是' if needs_refinement else '否'}")

            strengths = critique.get("strengths", [])
            if strengths:
                print("回复亮点：")
                for strength in strengths:
                    print(f"✅ {strength}")

            issues = critique.get("issues", [])
            if issues:
                print("发现问题点：")
                for i, issue in enumerate(issues, 1):
                    issue_type = issue.get("type", "unknown")
                    severity = issue.get("severity", "unknown")
                    description = issue.get("description", "No description")
                    suggestion = issue.get("suggestion", "No suggestion")

                    severity_emoji = {
                        "critical": "🔴",
                        "major": "🟠",
                        "minor": "🟡",
                        "suggestion": "🔵"
                    }.get(severity.lower(), "⚪")

                    print(f"{severity_emoji} {issue_type.title()} ({severity}): {description}")
                    print(f"💡 建议：{suggestion}")

            reasoning = critique.get("reasoning", "")
            if reasoning:
                print(f"推理过程：{reasoning}")

        elif event.type == EventType.REFLECTION_REFINEMENT:
            improvements = event.data.get("improvements", [])
            quality_improvement = event.data.get("quality_improvement", 0.0)

            if quality_improvement <= 0:
                print(f"✨ 响应优化完成。")
            else:
                print(f"✨ 响应优化完成。质量改进：+{quality_improvement:.2f}")

            if improvements:
                print("改进点：")
                for improvement in improvements:
                    print(f"🔧 {improvement}")

        elif event.type == EventType.REFLECTION_COMPLETE:
            final_quality = event.data.get("final_quality_score", 0.0)
            threshold_met = event.data.get("threshold_met", False)
            iterations = event.data.get("reflection_iterations", 0)
            total_improvements = event.data.get("total_improvements", 0)
            if threshold_met:
                print(f"✅ 完成反思，达到质量阈值！反思迭代次数：{iterations}，改进点：{total_improvements}。最终得分：{final_quality:.2f}")
            else:
                print(f"⚠️ 完成反思，未达质量阈值！反思迭代次数：{iterations}，改进点：{total_improvements}。最终得分：{final_quality:.2f}")

        elif event.type == EventType.COMPLETE:
            response = event.data.get("response", {})
            print(f"📊 总步骤数: {step_count}，⚡ 成功：{response.get('success', False)}")
            print(f"🎉 最终回复: ")
            print("-" * 50)
            print(f"{response.get('output', '无输出')}")
            print("-" * 50)
            break

        elif event.type == EventType.ERROR:
            print(f"❌ 失败：{event.data.get('error', '未知错误')}")
            break


if __name__ == "__main__":
    # query = "361的平方根是多少？再告诉我一些关于这个数的趣事。"
    query = "搜索并总结当今物理学发展概括，然后生成一份清晰的Markdown文本报告，最后调用PPT制作工具将Markdown文本转化为PPT。"
    asyncio.run(console_app(query))

